import { message } from 'ant-design-vue'
import axios from 'axios'
import router from '@/router'
const service = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 10000,
})

service.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
})

service.interceptors.response.use(response => {
    if (response.data.code === 403) {
        message.error('登录过期，请重新登录')
        localStorage.removeItem('token')
        router.push('/login')
    } else {
        return response.data
    }
}, error => {
    console.error('请求错误:', error)
    if (error.response) {
        if (error.response.status === 400) {
            message.error(error.response.data.message)
        } else if (error.response.status === 401) {
            message.error('未授权，请重新登录')
            localStorage.removeItem('token')
            router.push('/login')
        } else if (error.response.status === 500) {
            if (error.response.data.message) {
                message.error(error.response.data.message)
            } else {
                message.error('服务器内部错误')
            }
        } else {
            message.error(`请求失败: ${error.response.status}`)
        }
    }
    return Promise.reject(error)
})

export default service
